﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Barcode.DataMatrix;
using System.Drawing;
using System.Drawing .Imaging ;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.IO;


namespace MagicCube_v2_Demo
{
    public class DataMatrix
    {
        public Bitmap bmpBarcode;
        public string Header = "";
        //string txt;
        public char[] cpara = new char[22 * 22];
        public char[] data;
        public byte[] bBarcode = new byte[22 * 22];
        public string sBarcode;
        public char[] cBarcode = new char[22 * 22];
        int iPixel = 4;   //可选值4,5,7

        //引用动态链接库
        //[DllImport("DataMatrix.dll", EntryPoint = "dataMatrixEncode", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
        //public static extern int dataMatrixEncode(string barcode, int barsize, ref byte codedstr);
        //[DllImport("DataMatrix.dll", EntryPoint = "dataMatrixEncode1", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]

        //public static extern int dataMatrixEncode1(string barcode, int barsize, ref byte Dstr, int codedLen);

        [DllImport("DataMatrixEncoder.dll", EntryPoint = "dataMatrixEncode", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]

        //public static extern int dataMatrixEncode(string barcode);
        public static extern int dataMatrixEncode(string barcode, int barsize);

        public int CreateCode(string codestr)
        {
            if (codestr != String.Empty)
            {
                //textBox2.Text = ReplaceString(textBox2.Text.ToString().Trim());
                codestr = codestr.Trim();
                int result = dataMatrixEncode(codestr, 0);
                if (result == 0)
                {
                    StreamReader objReader = new StreamReader("CodedFlow.txt");
                    string sLine = objReader.ReadLine();
                    Header = sLine;
                    string[] split = sLine.Split(new Char[] { ' ', 'x' });
                    sLine = objReader.ReadLine();
                    int x = 0;
                    int n = Convert.ToInt32(split[0]);
                    while (sLine != null)
                    {
                        if (sLine != null)
                        {
                            string sTmp = sLine;
                            char[] cTmp = new char[22];
                            cTmp = sTmp.ToArray();
                            sBarcode += sTmp;
                            for (int i = 0; i < n; i++)
                            {
                                cpara[x] = cTmp[i];
                                x++;
                            }
                            sLine = objReader.ReadLine();
                        }
                    }

                    x = 0;
                    for (int j = 0; j < 22; j++)
                    {
                        for (int i = 0; i < 22; i++)
                        {
                            if (i < n && j < n)
                            {
                                cBarcode[j * 22 + i] = cpara[x];
                                x++;
                            }
                        }
                    }

                    //byte[] bTmp = new byte[22 * 22];
                    for (int i = 0; i < 22 * 22; i++)
                    {
                        if (cBarcode[i] == '1')
                            bBarcode[i] = 1;
                        else
                            bBarcode[i] = 0;
                    }
                    cBarcode = System.Text.Encoding.UTF8.GetChars(bBarcode);
                    bmpBarcode  = (Bitmap)RenderToBitmap(22, iPixel , cBarcode );

                    return n;
                }
            }

            return -1;
         
        }

        //对一个0,1矩阵根据NoOfBlocksPerAxis（块的个数），每个小块的2像素的大小生成一个位图
        private Bitmap RenderToBitmap(int NoOfBlocksPerAxis, int pixel, char[] Data)
        {
            int n = NoOfBlocksPerAxis;
            Bitmap bmp = new Bitmap((NoOfBlocksPerAxis + 2) * pixel, (NoOfBlocksPerAxis + 2) * pixel);
            Graphics g = Graphics.FromImage(bmp);
            g.FillRectangle(Brushes.White, 0, 0, (n + 2) * pixel, (n + 2) * pixel);
            for (int i = 0; i < Data.Length; i++)
            {
                if (Data[i] == '\0')
                    g.FillRectangle(Brushes.White, (i % n + 1) * pixel, (i / n + 1) * pixel, pixel, pixel);
                else
                    g.FillRectangle(Brushes.Black, (i % n + 1) * pixel, (i / n + 1) * pixel, pixel, pixel);
            }

            g.Dispose();
            return bmp;
        }

        //将0，1字符串存在一个一维数组中方便使用
        private char[] GetData(string str)
        {
            string[] splitHeader = Header.Split(new Char[] { ' ', 'x' });
            int n = Convert.ToInt32(splitHeader[0]);
            char[] data = new char[n * n];
            int j = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == '\r') continue;
                else if (str[i] == '\n') continue;
                else
                {
                    data[j] = str[i];
                    j++;
                }

            }

            return data;
        }

        //将字符串中的多个空格替换成一个空格
        private string ReplaceString(string str)
        {
            str = new System.Text.RegularExpressions.Regex("[\\s]+").Replace(str, " ");
            return str;
        }

        private string DataToString(char [] data)
        {
            string str = "";
            for (int i = 0; i < data.Length; i++)
            {
                if (i % Math.Sqrt(data.Length) == 0)
                {
                    str += System.Environment.NewLine;
                }
                str += data[i];

            }
            return str;
        }

        public string ReadCode(double[] dData)
        {
            if (dData != null)
            {
                bBarcode = new byte[22 * 22];
                for (int i = 0; i < 22 * 22; i++)
                {
                    bBarcode[i] = (byte)(int)dData[i];
                }
                for (int i = 0; i < 22 * 22; i++)
                {
                    sBarcode += bBarcode[i].ToString();
                }
                cBarcode = System.Text.Encoding.UTF8.GetChars(bBarcode);

                bmpBarcode = (Bitmap)RenderToBitmap(22, iPixel, cBarcode);
                List<string> result = DataMatrixDecoder.DecodeBarcode(bmpBarcode, false);
                if (result.Count > 0)
                {
                    string sInfo = result[0];
                    return sInfo;
                }
                else
                {
                    return "该图片中没有水印或已经损坏……";
                }
            }
            else
            {
                return "该图片中没有水印或已经损坏……";
            }
            
        }
    }
}
